import 'dart:io';

import 'package:concierge/app/models/login_type.dart';
import 'package:concierge/app/models/myvertu_user_bean.dart';
import 'package:concierge/app/pages/login/state.dart';
import 'package:concierge/app/req/apis/UserApi.dart';
import 'package:concierge/app/routes/app_routes.dart';
import 'package:concierge/app/widgets/CommonDialog.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:native_util/native_util.dart';

class LoginLogic extends GetxController {
  final state = LoginState();
  var isVertuPhone = true.obs;

  Future<void> loginType(LoginType type) async {
    isVertuPhone.value = type == LoginType.MY_VERTU;
    switch (type) {
      case LoginType.EMAIL:
        isVertuPhone.value = false;
        Get.toNamed(Routes.email_login);
        break;
      case LoginType.PHONE:
        Get.toNamed(Routes.phone_login);
        break;
      case LoginType.GOOGLE:
        UserApi.instance.loginByGoogle();
        break;
      case LoginType.MY_VERTU:
        if (await NativeUtil.checkMyVertuLoginStatus() == false) {
          showCommonDialog(
            content: "您还未安装MyVertu，不能通过MyVertu登录",
            dialogBtnParam: DialogButtonParam(
              onlyOneButton: true,
              showDivider: false,
              oneBtnText: "关闭",
            ),
          );
          return;
        }
        var res = await NativeUtil.loginByMyVertu();
        if (res == null) {
          SmartDialog.showToast("登录失败");
          return;
        }
        var user = await UserApi.instance.loginWithMyVertu(
          myvertuUserBeanFromJson(res),
        );
        if (user == null) {
          SmartDialog.showToast("登录失败");
          return;
        }
        Get.toNamed(Routes.main);
        break;
    }
  }

  @override
  void onInit() {
    super.onInit();
    init();
  }

  void init() {
    if (Platform.isIOS) {
      state.loginTypes.addAll(
        LoginType.values.where((m) => m != LoginType.MY_VERTU),
      );
    } else {
      state.loginTypes.addAll(LoginType.values);
    }
  }
}
